/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lyh.metrics.api;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

public class ThreadPoolMetricRegistry {
    private static final MetricRegistry             metricRegistry   = new MetricRegistry();
    private static final ThreadLocal<Timer.Context> timerThreadLocal = new ThreadLocal<>();

    public static MetricRegistry metricRegistry() {
        return metricRegistry;
    }

    public static ThreadLocal<Timer.Context> timerThreadLocal() {
        return timerThreadLocal;
    }

    /**
     * 创建一个实现了监控的定时任务线程池
     *
     * @return
     */
    public static ScheduledExecutorService newMetricsScheduled() {
        return new MetricScheduledThreadPoolExecutor(10, "testScheduledThreadPool");
    }

    /**
     * 自定义定时任务执行器线程池(实现定时任务的统计)
     */
    public static class MetricScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
        String name;

        public MetricScheduledThreadPoolExecutor(int corePoolSize, String name) {
            super(corePoolSize);
            this.name = name;
        }

        public MetricScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, String name) {
            super(corePoolSize, threadFactory);
            this.name = name;
        }

        public MetricScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler, String name) {
            super(corePoolSize, handler);
            this.name = name;
        }

        public MetricScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory,
                                                 RejectedExecutionHandler handler, String name) {
            super(corePoolSize, threadFactory, handler);
            this.name = name;
        }

        @Override
        protected void beforeExecute(Thread t, Runnable r) {
            super.beforeExecute(t, r);
            try {
                ThreadPoolMetricRegistry.timerThreadLocal() //
                    .set(ThreadPoolMetricRegistry.metricRegistry().timer("scheduledThreadPool." + name).time());
            } catch (final Throwable ignored) {
                // ignored
            }
        }

        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);
            try {
                final ThreadLocal<Timer.Context> tl = ThreadPoolMetricRegistry.timerThreadLocal();
                final Timer.Context ctx = tl.get();
                if (ctx != null) {
                    ctx.stop();
                    tl.remove();
                }
            } catch (final Throwable ignored) {
                // ignored
            }
        }
    }
}
